package com.yidingdui.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yidingdui.config.JwtProperties;
import com.yidingdui.domain.dto.UserLoginDTO;
import com.yidingdui.domain.dto.UserRegisterDTO;
import com.yidingdui.domain.entity.User;
import com.yidingdui.domain.vo.Resultdata;
import com.yidingdui.domain.vo.UserVO;
import com.yidingdui.exception.BadRequestException;
import com.yidingdui.mapper.UserMapper;
import com.yidingdui.service.IUserService;
import com.yidingdui.util.BeanUtils;
import com.yidingdui.util.JwtTool;
import com.yidingdui.domain.dto.ChangePasswordDTO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    private final PasswordEncoder passwordEncoder;

    private final JwtTool jwtTool;

    private final JwtProperties jwtProperties;

    private final UserMapper userMapper;
    @Override
    public UserVO login(UserLoginDTO loginDTO) {
        // 1.数据校验
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        // 2.根据用户名或手机号查询
        User user = userMapper.getUserByUsername(username);
        Assert.notNull(user, "用户名错误");

        // 3.校验密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BadRequestException("用户名或密码错误");
        }
        // 4.生成TOKEN
        String token = jwtTool.createToken(user.getId(), jwtProperties.getTokenTTL());
        // 5.封装VO返回
        UserVO vo = new UserVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setToken(token);
        return vo;
    }

    @Override
    public Resultdata<UserVO> register(UserRegisterDTO registerDTO) {
        // 验证用户名是否已存在
        if (userMapper.countByUsername(registerDTO.getUsername()) > 0) {
            return Resultdata.error("400", "用户名已被使用");
        }

        // 验证邮箱是否已存在
        if (registerDTO.getEmail() != null && !registerDTO.getEmail().isEmpty() &&
                userMapper.countByEmail(registerDTO.getEmail()) > 0) {
            return Resultdata.error("400", "邮箱已被注册");
        }

        // 验证手机号是否已存在
        if (registerDTO.getPhone() != null && !registerDTO.getPhone().isEmpty() &&
                userMapper.countByPhone(registerDTO.getPhone()) > 0) {
            return Resultdata.error("400", "手机号已被注册");
        }

        // 创建用户实体
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);

        // 加密密码
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));

        // 设置时间
        LocalDateTime now = LocalDateTime.now();
        user.setCreatedAt(now);
        user.setUpdatedAt(now);

        // 插入数据库
        int result = userMapper.insertUser(user);
        if (result <= 0) {
            return Resultdata.error("500", "注册失败，请稍后重试");
        }

        // 创建返回对象
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);

        return Resultdata.success(userVO);
    }

    @Override
    public UserVO getCurrentUserInfo(Long userId) {
        if (userId == null) {
            throw new BadRequestException("未登录");
        }
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new BadRequestException("用户不存在");
        }
        UserVO vo = new UserVO();
        BeanUtils.copyProperties(user, vo);
        return vo;
    }

    @Override
    public void changePassword(Long userId, ChangePasswordDTO dto) {
        if (userId == null) {
            throw new BadRequestException("未登录");
        }
        User user = userMapper.getById(userId);
        if (user == null) {
            throw new BadRequestException("用户不存在");
        }
        if (!passwordEncoder.matches(dto.getOldPassword(), user.getPassword())) {
            throw new BadRequestException("原密码不正确");
        }
        String encoded = passwordEncoder.encode(dto.getNewPassword());
        user.setPassword(encoded);
        user.setUpdatedAt(java.time.LocalDateTime.now());
        // 使用自定义SQL更新密码，避免MyBatis-Plus默认语句绑定问题
        userMapper.updateUserPassword(user);
    }
}
